package com.heima.kafka.stream;

import org.apache.kafka.streams.KeyValue;
import org.apache.kafka.streams.StreamsBuilder;
import org.apache.kafka.streams.kstream.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;
import java.util.Arrays;

/**
 * @author brianxia
 * @version 1.0
 * @date 2022-09-27 10:56
 */
@Configuration
public class KafkaStream106 {

    @Bean
    public KStream<String,String> stream(StreamsBuilder builder){
        //第一要素，数据来源
        KStream<String, String> stream = builder.stream("itcast-topic-input");
        //第二要素，数据处理器
        //to 第三要素，发送到topic中
        stream.flatMapValues((ValueMapper<String, Iterable<String>>) value -> {
                    //"hello kafka" -> List<String> hello kafka
                    return Arrays.asList(value.split(" "));
                }).groupBy((key, value) -> value)
                .windowedBy(TimeWindows.of(Duration.ofSeconds(10)))
                .count()
                .toStream()
                .map((KeyValueMapper<Windowed<String>, Long, KeyValue<String, String>>) (key, value)
                        -> new KeyValue<>(key.key(),value.toString()))
                .to("itcast-topic-out");

        return stream;
    }
}
